using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Utils
{
    public class HttpUtil
    {
        /// <summary>
        /// HttpGet请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="appendStr">地址栏拼接字符串</param>
        /// <returns></returns>
        public static string Get(string Url, string appendStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (appendStr == "" ? "" : "?") + appendStr);
            request.Method = "GET";
            request.ContentType = "text/html;charset=UTF-8";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            return retString;
        }



        /// <summary>
        /// HttpPost请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">Json字符串</param>
        /// <returns></returns>
        public static string Post(string Url, string postDataStr)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }



        /// <summary>
        /// HttpPost请求
        /// </summary>
        /// <param name="Url">请求地址</param>
        /// <param name="postDataStr">Json字符串</param>
        /// <param name="cookieStr">Cookie字符串</param>
        /// <returns></returns>
        public static string Post(string Url, string postDataStr,string cookieStr)
        {
            CookieContainer cookie = new CookieContainer();
            string[] param = cookieStr.Split(';');
            foreach (string item in param)
            {
                string name = item.Substring(0, item.IndexOf('=')).Trim();
                string value = item.Substring(item.IndexOf('=') + 1).Trim();
                Cookie cookies = new Cookie(name, value, "", "settle.cbbs.tmall.com");
                cookie.Add(cookies);
            }
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = Encoding.UTF8.GetByteCount(postDataStr);
            request.CookieContainer = cookie;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //response.Cookies = cookie.GetCookies(response.ResponseUri);
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return retString;
        }

        /// <summary>
        /// HttpWebRequest接口请求函数(传入cookie)
        /// </summary>
        /// <param name="PageURL">请求的url</param>
        /// <param name="str">登陆参数</param>
        /// <returns></returns>
        public static String RGetPageCode_Cookie3(String PageURL, string str)
        {
            string domain = PageURL.Split('/')[2];
            CookieContainer cookie = new CookieContainer();
            string[] param = str.Split(';');
            foreach (string item in param)
            {
                string name = item.Substring(0, item.IndexOf('=')).Trim();
                string value = item.Substring(item.IndexOf('=') + 1).Trim();
                Cookie cookies = new Cookie(name, value, "", domain);
                cookie.Add(cookies);
            }
            String strHtml = "";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PageURL);
            request.Method = "GET";
            request.ContentType = "text/html";
            //request.Accept = "text/html";
            request.Timeout = Int32.MaxValue;
            request.CookieContainer = cookie;
            //置为fasle，是为了防止超时
            request.ServicePoint.Expect100Continue = false;
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    if (response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.OK && request.HaveResponse)
                        {
                            using (Stream stream = response.GetResponseStream())//获取返回的字符流格式
                            {
                                using (StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8))//解决乱码：设置utf-8字符格式
                                {
                                    if (sr != null)
                                    {
                                        strHtml = sr.ReadToEnd();
                                    }
                                }
                            }
                        }

                    }
                }
            }
            request = null;
            //GZip压缩后要用到这个
            //System.IO.StreamReader r = new System.IO.StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress), encode);
            return strHtml;
        }

    }
}
